﻿//********************************************************************************//
//创建日期：<创建日期，2016-09-21>
//创建作者：<孙雪婷，sunxueting@shanghai3h.com>
//功能说明：抄表数据录入
//********************************************************************************//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Class;
using System.Data;
using Entity;
using BLL;
using BLL.Access;
using Platform.Http;

namespace Web.Pages.QuShui.DiXiaS.ChaoBiaoGL
{
    public partial class ChaoBiaoSJLR : BasePage
    {
        #region 属性

        /// <summary>
        /// 用户号
        /// </summary>
        private string YongHuH
        {
            get
            {
                return ViewState["_YongHuH"] as string;
            }
            set
            {
                ViewState["_YongHuH"] = value;
            }
        }

        /// <summary>
        /// 水井号
        /// </summary>
        private string ShuiJingH
        {
            get
            {
                return ViewState["_ShuiJingH"] as string;
            }
            set
            {
                ViewState["_ShuiJingH"] = value;
            }
        }

        /// <summary>
        /// 水表号
        /// </summary>
        private string ShuiBiaoH
        {
            get
            {
                return ViewState["_ShuiBiaoH"] as string;
            }
            set
            {
                ViewState["_ShuiBiaoH"] = value;
            }
        }

        #endregion

        #region 变量

        /// <summary>
        /// 数据访问操作类
        /// </summary>
        SpHelper _spHelper = new SpHelper();

        /// <summary>
        /// 用户信息BLL
        /// </summary>
        QS_YG_YONGHUXXBLL _YHXXBLL = new QS_YG_YONGHUXXBLL();

        /// <summary>
        /// 深井信息BLL
        /// </summary>
        QS_YH_SHENJINGXXBBLL _SJXXBLL = new QS_YH_SHENJINGXXBBLL();

        /// <summary>
        /// 取水口信息bll
        /// </summary>
        QS_YH_QUSHUIKXXBBLL _QSKBLL = new QS_YH_QUSHUIKXXBBLL();

        /// <summary>
        /// 水表信息bll
        /// </summary>
        QS_YH_SHUIBIAOXXBBLL _SBXXBLL = new QS_YH_SHUIBIAOXXBBLL();

        /// <summary>
        /// 抄表数据BLL
        /// </summary>
        QS_CB_CHAOBIAOSJ _CBSJ = new QS_CB_CHAOBIAOSJ();

        /// <summary>
        /// 抄表数据BLL
        /// </summary>
        QS_CB_CHAOBIAOSJBLL _CBSJBLL = new QS_CB_CHAOBIAOSJBLL();
        /// <summary>
        /// 日志BLL
        /// </summary>
        SYS_LOGBLL _SYS_LOGBLL = new SYS_LOGBLL();

        #endregion

        #region 事件

        /// <summary>
        /// 页面加载事件
        /// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            //第一次页面加载
            if (!IsPostBack)
            {
                InitData();
                LoadData();
                Display();
                FocusChange();
            }
            LoadData();
            //将当前页面对像传递给确认控件

        }

        /// <summary>
        /// 树聚焦行改变事件
        /// </summary>
        protected void treeChaoBiaoSH_FocusedNodeChanged(object sender, EventArgs e)
        {
            FocusChange();
        }

       
        /// <summary>
        /// 修改操作
        /// </summary>
        protected void btnEdit_Click(object sender, EventArgs e)
        {
            this.Status = GridViewStatus.Update;
            Display();
        }

        /// <summary>
        /// 放弃操作
        /// </summary>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            this.Status = GridViewStatus.Init;
            FocusChange();
            Display();
        }

        /// <summary>
        /// 保存操作
        /// </summary>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (ValidateData())
            {
                SaveData();
            }
        }
        /// <summary>
        /// 保存验证
        /// </summary>
        /// <returns></returns>
        private bool ValidateData()
        {
            if (!PageTools.ValidateString(this.txtBenYueCH.Text, PageTools.eValidateType.数字))
            {
                PageTools.AlertMsg(this, "你输入的本月抄码格式不正确，请输入数字类型。");
                this.txtBenYueCH.Focus();
                return false;
            }
            if (!PageTools.ValidateString(this.txtBenYueSL.Text, PageTools.eValidateType.数字))
            {
                PageTools.AlertMsg(this, "你输入的本月水量格式不正确，请输入数字类型。");
                this.txtBenYueSL.Focus();
                return false;
            }
            //验证该水表是否为此用户的有效水表
            DataTable dt_sb = _SBXXBLL.SelectQS_YH_SHUIBIAOXXBsDynamic(string.Format(@"i_jlzt=0 and s_shuibiaobh='{1}' and S_QUSHUIK='{2}' 
 and exists (select 1 from qs_yh_yonghusbgx where s_shuibiaoh='{1}' and s_yonghuh='{0}' and i_jlzt=0)", txtYongHuH.Text, txtShuiBiaoBH.Text, txtJingBH.Text), null);
            if (dt_sb.Rows.Count < 1)
            {
                PageTools.AlertMsg(this, "此水表号不是该用户下的有效水表，请重新输入");
                this.txtShuiBiaoBH.Focus();
                return false;
            }
            if (this.txtChaoBiaoZT.Text=="")
            {
                PageTools.AlertMsg(this, "抄表状态为空，请输入！");
                this.txtChaoBiaoZT.Focus();
                return false;
            }
            return true;
        }

        /// <summary>
        /// 隐藏按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hidden_Click(object sender, EventArgs e)
        {
            this.treeChaoBiaoSH.FindNodeByKeyValue(txtYongHuH.Text).Focus();
        }
        #endregion

        #region 方法

       
        

        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitData()
        {
            span1.InnerText = BusinessTool.WType == 1 ? "取水口编号" : "井编号：";
            txtBenYueDL.ClientEnabled = BusinessTool.WType == 1 ? true : false;
            //水量年月
            txtShuiLiangYM.Text = BusinessTool.GetSLYMorZWNY(1,BusinessTool.WType).ToString();
            LoadCH();
            txtYongHuH.Focus();
        }

        /// <summary>
        /// 加载册号
        /// </summary>
        private void LoadCH()
        {
            string[] arr = { "001", "002", "003", "005", "008", "009", "101", "106", "111", "113", "115", "204", "207", "208", "209", "210", "213", "214", "216", "217", "218" };
            for (int i = 0; i < arr.Length; i++)
            {
                cbmCeHao.Items.Add(arr[i], arr[i]);
            }
        }
        /// <summary>
        /// 数据加载
        /// </summary>
        private void LoadData()
        {
            int wtype = BusinessTool.WType;
            var ds = _spHelper.P_QSCB_CHAOBIAOSJ(wtype);
            if (null != ds && ds.Tables.Count > 0)
            {
                var table = ds.Tables[0];
                treeChaoBiaoSH.KeyFieldName = "BIANHAO1";
                treeChaoBiaoSH.ParentFieldName = "BIANHAO2";
                treeChaoBiaoSH.DataSource = table;
                treeChaoBiaoSH.DataBind();
            }
        }

        /// <summary>
        ///用于控制添加、修改、查看三种状态的显示
        /// </summary>
        private void Display()
        {
            switch (this.Status)
            {
                case GridViewStatus.Init:
                    this.btnSave.Visible = true;
                    this.btnCancel.Visible = true;
                    this.treeChaoBiaoSH.Enabled = true;
                    //SetText(false);
                    break;
                case GridViewStatus.Search:
                    //SetText(false);
                    break;
                case GridViewStatus.Update:
                    this.btnSave.Visible = true;
                    this.btnCancel.Visible = true;
                    this.treeChaoBiaoSH.Enabled = false;
                    //SetText(true);
                    break;
                case GridViewStatus.Add:
                    this.btnSave.Visible = true;
                    this.btnCancel.Visible = true;
                    this.treeChaoBiaoSH.Enabled = false;
                    //SetText(true);
                    InitData();
                    break;
            }
        }

       

        /// <summary>
        /// 保存数据
        /// </summary>
        private void SaveData()
        {
            int ym = Convert.ToInt32(txtShuiLiangYM.Text);
            int i_y = ym / 100;
            int i_m = ym % 100;
            OperateState operateState;
            int id = 0;
            DataTable dt_cb = _CBSJBLL.SelectQS_CB_CHAOBIAOSJsDynamic(string.Format("s_yonghuh='{0}' and s_shuibiaobh='{1}' and s_jingbh='{2}' and i_jlzt=0 and  i_y={3} and i_m={4}", txtYongHuH.Text, txtShuiBiaoBH.Text, txtJingBH.Text,i_y,i_m), null);
            if (dt_cb.Rows.Count > 0)
            {
                id = Convert.ToInt32(dt_cb.Rows[0]["ID"]);
                //修改操作
                operateState = OperateState.Modify;
                this._CBSJ = this._CBSJBLL.SelectQS_CB_CHAOBIAOSJ(id);
                this._CBSJ.ID = id;
            }
            //添加
            else 
            {
                operateState = OperateState.Add;
                this._CBSJ.ID = 0;
                this._CBSJ.S_SHUIBIAOBH = txtShuiBiaoBH.Text;
                this._CBSJ.I_Y = i_y;
                this._CBSJ.I_M = i_m;
                this._CBSJ.I_JIHUASL = Convert.ToDecimal(txtBenYueSL.Text);
                this._CBSJ.S_YONGHUH = txtYongHuH.Text;
                this._CBSJ.S_JINGBH = txtJingBH.Text;
                this._CBSJ.S_CEHAO = cbmCeHao.Text;
                this._CBSJ.S_SHUILIANGLB = txtShuiLiangLB.Text;
                this._CBSJ.S_TIANJIAR = LoginInfo.CurrentUser.Account;
                this._CBSJ.D_CAOZUORQ = BusinessTool.GetDataBaseDateTime();
                this._CBSJ.N_SHUIJIA = Convert.ToDecimal(txtShuiJia.Text);
            }
          
            this._CBSJ.I_JLZT = 0;
            this._CBSJ.I_CHAOBIAOZT = Convert.ToDecimal(txtChaoBiaoZT.Text);
            this._CBSJ.I_BENYUECM = Convert.ToDecimal(txtBenYueCH.Text);
            this._CBSJ.I_BENYUESL = Convert.ToDecimal(txtBenYueSL.Text);
            this._CBSJ.S_CAOZUOR = LoginInfo.CurrentUser.Account;
            this._CBSJ.D_CAOZUORQ = BusinessTool.GetDataBaseDateTime();
            this._CBSJ.I_SHUILIANGDL = txtBenYueDL.Text == "" ? 0 : Convert.ToDecimal(txtBenYueDL.Text);

           //同时修改水表信息表里面的册号
            string res = "";
            _spHelper.P_QSCB_XGCH(BusinessTool.WType, txtShuiLiangLB.Text, cbmCeHao.Text, out res);

            bool result = this._CBSJBLL.InsertOrUpdate(_CBSJ);
            //执行操作
            if (result)
            {
                _SYS_LOGBLL.Log<QS_CB_CHAOBIAOSJ>(LoginInfo.CurrentUser, WordsStruct.I_YEWULX.地下水.ToString(), "抄表数据录入", operateState, _CBSJ, null);
                PageTools.AlertMsg(this, "保存成功！");
                LoadData();
                this.Status = GridViewStatus.Init;
                Display();
                //设置选中当前操作的项
                this.treeChaoBiaoSH.FindNodeByKeyValue(this._CBSJ.S_YONGHUH).Focus();
                //更新当前操作项ID
                //this.GuanLiKuaiID = Convert.ToInt32(((System.Data.DataRowView)(treeChaoBiaoSH.FocusedNode.DataItem)).Row.ItemArray[0].ToString().Split('_')[0]);
            }
            else
            {
                PageTools.AlertMsg(this, "保存失败！");
            }
        }

        /// <summary>
        /// 给输入框赋值
        /// </summary>
        private void SetData()
        {
            int y = Convert.ToInt32(txtShuiLiangYM.Text) / 100;
            int m = Convert.ToInt32(txtShuiLiangYM.Text) % 100;
            DataTable dt_yh = _YHXXBLL.SelectQS_YG_YONGHUXXesDynamic(string.Format("i_jlzt=0 and s_yonghuh='{0}'", this.YongHuH), null);
            if (BusinessTool.WType == 2)
            {
                DataTable dt_sj = _SJXXBLL.SelectQS_YH_SHENJINGXXBsDynamic(string.Format("i_jlzt=0 and  S_JINGBH='{0}'", this.ShuiJingH), null);
                txtJingBH.Text = dt_sj.Rows.Count > 0 ? dt_sj.Rows[0]["S_JINGBH"].ToString() : "";
                txtQuShuiDD.Text = dt_sj.Rows.Count > 0 ? dt_sj.Rows[0]["S_JINGDIZ"].ToString() : "";
            }
            else
            {
                DataTable dt_qsk = _QSKBLL.SelectQS_YH_QUSHUIKXXBsDynamic(string.Format("i_jlzt=0 and  S_QUSHUIKBH='{0}'", this.ShuiJingH), null);
                txtJingBH.Text = dt_qsk.Rows.Count > 0 ? dt_qsk.Rows[0]["S_QUSHUIKBH"].ToString() : "";
                txtQuShuiDD.Text = dt_qsk.Rows.Count > 0 ? dt_qsk.Rows[0]["S_QUSHUIDZ"].ToString() : "";
            }
           
            DataTable dt_sb = _SBXXBLL.SelectQS_YH_SHUIBIAOXXBsDynamic(string.Format("i_jlzt=0 and S_SHUIBIAOBH='{0}'", this.ShuiBiaoH), null);
            DataTable dt_cb = _CBSJBLL.SelectQS_CB_CHAOBIAOSJsDynamic(string.Format("s_yonghuh='{0}' and s_shuibiaobh='{1}' and s_jingbh='{2}' and i_jlzt=0 and i_y={3} and i_m={4}", this.YongHuH, this.ShuiBiaoH, this.ShuiJingH, y, m), null);
            int y_sy = 0; int m_sy = 0;
            if (m == 1)
            {
                m_sy = 12;
                y_sy = y - 1;
            }
            else {
                m_sy = m-1;
                y_sy = y;
            }
            DataTable dt_cb_sy = _CBSJBLL.SelectQS_CB_CHAOBIAOSJsDynamic(string.Format("s_yonghuh='{0}' and s_shuibiaobh='{1}' and s_jingbh='{2}' and i_jlzt=0 and i_y={3} and i_m={4}", this.YongHuH, this.ShuiBiaoH, this.ShuiJingH, y_sy, m_sy), null);

            if (dt_cb_sy.Rows.Count>0)
            {
                txtYongHuH.Text = dt_yh.Rows[0]["S_YONGHUH"].ToString();
                txtYongHuM.Text = dt_yh.Rows[0]["S_YONGHUM"].ToString();
                txtShuiJia.Text = dt_yh.Rows[0]["N_SHUIJIA"].ToString();
            }
            
            cbmCeHao.Text = dt_sb.Rows[0]["S_CEHAO"].ToString();
            txtShuiBiaoBH.Text = dt_sb.Rows[0]["S_SHUIBIAOBH"].ToString();
            string sllb = dt_sb.Rows[0]["S_SHUILIANGLB"].ToString();
            if (sllb == "1")
            {
                txtShuiLiangLB.Text = "普通采";
            }
            else if (sllb == "2")
            {
                txtShuiLiangLB.Text = "采灌采";
            }
            else if (sllb == "3")
            {
                txtShuiLiangLB.Text = "采灌灌";
            }
            else if (sllb == "4")
            {
                txtShuiLiangLB.Text = "矿泉采";
            }
            else if (sllb == "5")
            {
                txtShuiLiangLB.Text = "专灌";
            }
            txtChaoBiaoZT.Text = dt_cb.Rows.Count > 0 ? dt_cb.Rows[0]["I_CHAOBIAOZT"].ToString() : "";
            txtBenYueCH.Text = dt_cb.Rows.Count > 0 ? dt_cb.Rows[0]["I_BENYUECM"].ToString() : "";
            txtBenYueSL.Text = dt_cb.Rows.Count > 0 ? dt_cb.Rows[0]["I_BENYUESL"].ToString() : "";
            txtShangYueCM.Text = dt_cb_sy.Rows.Count > 0 ? dt_cb_sy.Rows[0]["I_BENYUECM"].ToString() : "0";
            txtShangYueSL.Text = dt_cb_sy.Rows.Count > 0 ? dt_cb_sy.Rows[0]["I_BENYUESL"].ToString() : "0";
            txtKaiZhangSL.Text = dt_cb.Rows.Count > 0 ? dt_cb.Rows[0]["I_JIHUASL"].ToString() : "0";
            txtBenYueDL.Text = dt_cb.Rows.Count > 0 ? dt_cb.Rows[0]["I_SHUILIANGDL"].ToString() : "0";
            txtKaiZhangDL.Text = dt_cb.Rows.Count > 0 ? dt_cb.Rows[0]["I_JIHUASLDL"].ToString() : "0";
            txtChaoBiaoZT.Focus();

        }

        /// <summary>
        /// 左侧列表树焦点变更方法
        /// </summary>
        private void FocusChange()
        {
            if (null != treeChaoBiaoSH.FocusedNode)
            {
                var node = treeChaoBiaoSH.FocusedNode;
                if (node.Level == 1)//第一级 用户号
                {
                    if (node.ChildNodes.Count > 0)
                    {
                        var childNode = node.ChildNodes[0];
                        int yhh_id = Convert.ToInt32(((System.Data.DataRowView)(node.DataItem)).Row.ItemArray[0].ToString().Split('_')[0]);
                        string [] arr = node.Key.Split('(');
                        this.YongHuH = arr[0].ToString();//用户号
                        this.ShuiJingH = childNode.Key;//井
                        if (childNode.ChildNodes.Count > 0)
                        {
                            this.ShuiBiaoH = childNode.ChildNodes[0].Key;//水表
                        }

                    }
                }
                else if (node.Level == 2)//第二级 水井号/取水口编号
                {
                    this.YongHuH = node.ParentNode.Key;//用户号
                    this.ShuiJingH = node.Key;//井
                    if (node.ChildNodes.Count > 0)
                    {
                        this.ShuiBiaoH = node.ChildNodes[0].Key;//水表
                    }
                }
                else if (node.Level == 3)//第三级 水表号
                {
                    this.YongHuH = node.ParentNode.ParentNode.Key;//用户号
                    this.ShuiJingH = node.ParentNode.Key;//井
                    this.ShuiBiaoH = node.Key;//水表
                }
            }
            SetData();
        }

        /// <summary>
        /// 响应前台回调
        /// </summary>
        protected void ASPxCallback1_Callback(object source, DevExpress.Web.CallbackEventArgs e)
        {
            int y = Convert.ToInt32(txtShuiLiangYM.Text) / 100;
            int m = Convert.ToInt32(txtShuiLiangYM.Text) % 100;
            string yhh = this.hdCollection.Get("yhh").ToString();
            string msg = "";
            if (e.Parameter == "info")
            {
                DataTable dt_yh = _YHXXBLL.SelectQS_YG_YONGHUXXesDynamic(string.Format("i_jlzt=0 and s_yonghuh='{0}'", yhh), null);

                DataTable dt_sj = BusinessTool.WType == 2 ? _SJXXBLL.SelectQS_YH_SHENJINGXXBsDynamic(string.Format("S_JINGBH in (select S_JINGBIANH from QS_YH_YONGHUSJGXB where i_jlzt=0 and S_YONGHUBH='{0}') and i_jlzt=0", yhh), null) : null;
                DataTable dt_qsk = BusinessTool.WType == 1 ? _QSKBLL.SelectQS_YH_QUSHUIKXXBsDynamic(string.Format("S_QUSHUIKBH in (select S_QUSHUIKH from QS_YH_YONGHUQSKGX where i_jlzt=0 and S_YONGHUH='{0}') and i_jlzt=0", yhh), null) : null;

                DataTable dt_sb = _SBXXBLL.SelectQS_YH_SHUIBIAOXXBsDynamic(string.Format("S_SHUIBIAOBH in (select S_SHUIBIAOH from QS_YH_YONGHUSBGX where i_jlzt=0 and  S_YONGHUH='{0}') and i_jlzt=0", yhh), null);

                string bh = BusinessTool.WType == 2 ? dt_sj.Rows[0]["S_JINGBH"].ToString() : dt_qsk.Rows[0]["S_QUSHUIKBH"].ToString();
                string dz = BusinessTool.WType == 2 ? dt_sj.Rows[0]["S_JINGDIZ"].ToString() : dt_qsk.Rows[0]["S_QUSHUIDZ"].ToString();
                DataTable dt_cb = _CBSJBLL.SelectQS_CB_CHAOBIAOSJsDynamic(string.Format("s_yonghuh='{0}' and s_shuibiaobh='{1}' and s_jingbh='{2}' and i_jlzt=0 and i_y={3} and i_m={4}", yhh, dt_sb.Rows[0]["S_SHUIBIAOBH"].ToString(), bh, y, m), null);

                int y_sy = 0; int m_sy = 0;
                if (m == 1)
                {
                    m_sy = 12;
                    y_sy = y - 1;
                }
                else
                {
                    m_sy = m - 1;
                    y_sy = y;
                }
                DataTable dt_cb_sy = _CBSJBLL.SelectQS_CB_CHAOBIAOSJsDynamic(string.Format("s_yonghuh='{0}' and s_shuibiaobh='{1}' and s_jingbh='{2}' and i_jlzt=0 and i_y={3} and i_m={4}", yhh, dt_sb.Rows[0]["S_SHUIBIAOBH"].ToString(), bh, y_sy, m_sy), null);

                if (dt_cb.Rows.Count > 0)
                {
                    msg = string.Join("|", dt_yh.Rows[0]["S_YONGHUM"].ToString(), dt_yh.Rows[0]["N_SHUIJIA"].ToString(), bh, dz,
                   dt_sb.Rows[0]["S_CEHAO"].ToString(), dt_sb.Rows[0]["S_SHUIBIAOBH"].ToString(), dt_sb.Rows[0]["S_SHUILIANGLB"].ToString(),
                   dt_cb.Rows[0]["I_CHAOBIAOZT"].ToString(), dt_cb.Rows[0]["I_BENYUECM"].ToString(), dt_cb.Rows[0]["I_BENYUESL"].ToString(),
                   dt_cb_sy.Rows[0]["I_BENYUECM"].ToString(), dt_cb_sy.Rows[0]["I_BENYUESL"].ToString(),
                   dt_cb.Rows[0]["I_JIHUASL"].ToString(), dt_cb.Rows[0]["I_SHUILIANGDL"].ToString(), dt_cb.Rows[0]["I_JIHUASLDL"].ToString()
                   );
                }
                else
                {
                    msg = string.Join("|", dt_yh.Rows[0]["S_YONGHUM"].ToString(), dt_yh.Rows[0]["N_SHUIJIA"].ToString(), bh, dz,
                        dt_sb.Rows[0]["S_CEHAO"].ToString(), dt_sb.Rows[0]["S_SHUIBIAOBH"].ToString(), dt_sb.Rows[0]["S_SHUILIANGLB"].ToString(),
                        "", "", "", "", "", "", "", "");
                }
                e.Result = e.Parameter + "|0|" + msg;
            }
            this.treeChaoBiaoSH.FindNodeByKeyValue(yhh).Focus();
        }
        
        #endregion       

    }
}